<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use DB;
use Cache;
use Redis;
use App\Http\Controllers\Api\KongSaiEnController;
class ChuApiController extends Controller
{
    public function timer(){
        //更新控塞恩温湿度大气压
        $this->upKsenTemHum();
        $this->upPress();
    }
    //控塞恩服务器温湿度每n分钟更新一次获取
    private function upKsenTemHum(){
        $com_lan_ips = DB::table('a_station')->where('com_lan_ip','!=','')->pluck('com_lan_ip');
        $hb6303 = DB::table('a_hb6303')->pluck('id','dev_num');
        $envInfo = [];
        foreach ($com_lan_ips as $key => $ip) {
            $ksenApi = new KongSaiEnController($ip);
            $res = $ksenApi->login();
            if($res){
                $res = json_decode($res,true);
               if ($res['code'] == 1000) {
                // dd($res);
                $userId = $res['data']['userId'];
                $res = $ksenApi->GetDeviceData($userId);
                $res = json_decode($res,true);
                if ($res && $res['code'] == 1000) {
                    foreach ($res['data'] as $item) {
                        if ($item['deviceStatus'] == 2) {
                            $devNum = $item['deviceAddr'];
                            if(!isset($hb6303[$devNum])){
                                $id6303 = DB::table('a_hb6303')->insertGetId(['dev_num'=>$devNum,'pos'=>'试验区','type'=>'temp_hum','dev_type'=>'ksen']);
                                if ($id6303) {
                                    $hb6303[$devNum] = $id6303;
                                }
                            }
                            $envInfo[] = [
                                'temp'=>$item['realTimeData'][0]['dataValue'],
                                'humi'=>$item['realTimeData'][1]['dataValue'],
                                'dev_num'=>$devNum,
                                'hb6303_id'=>$hb6303[$devNum],
                            ];
                        }
                    }
                }
            } 
            }
            
        }
        if($envInfo){
             DB::table('a_env_info')->insert($envInfo);
        }
       
    }
    
    //更新大气压
    public function upPress(){
        $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp"));  // 创建Socket
        $item = DB::table('a_hb6303')->where('type','press')->first();
        try{
            $sendStr = '01 03 00 00 00 03 05 CB';
            $ip = '192.168.8.147';
            $port = 8000;
            if (!$sendStr || !$ip || !$port) {
                info($sendStr.$ip.$port.'或错误！');
                return '参数错误';
            }
            
            $sendStr = str_replace(' ', '', $sendStr);
            $sendStr = hex2bin(preg_replace('# #', '', $sendStr));
            $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp"));  // 创建Socket
            $connection = socket_connect($socket, $ip, $port);
            // $connection = socket_connect($socket, "192.168.8.181", 8000);
            info("连接状态：$connection");
            if ($connection) {  //连接
                //向打开的套集字写入数据（发送数据）
                $st=$sendStr;
                $length = strlen($st);
                $s = socket_write($socket, $st, $length);
                //从套接字中获取服务器发送来的数据
                $msg = socket_read($socket,8190);
                $msg = bin2hex($msg);
                info("16进制返回数据:");
                // echo $msg;
                $temp = $pressure = '';
                // info(substr($msg,0,18));
                // if(substr($msg,0,-8) === '000000000007010304') //温湿度
                $pressure = hexdec(substr($msg,6,4))/10;
                // info(substr($msg,6,4));
                $temp = strtolower(substr($msg,10,2)) == 'ff' ? hexdec(substr($msg,12,2))/10 : hexdec(substr($msg,10,4))/10;
                if ($temp || $pressure ) {
                    DB::table('a_env_info')->insert(['temp'=>$temp,'pressure'=>$pressure,'hb6303_id'=>$item->id,'dev_num'=>$item->dev_num]);
                }
                info("大气压环境设备获取数据：$msg");
                info("大气压设备：$item->dev_num");
                // echo $msg." \n";
                $res = 1;
            }else{
                $res = 'socket连接失败！';
            }
        }catch(\Exception $exception){
            // dd($exception->getMessage(),$exception->getLine());
            info('大气压设备获取数据有误：'.$exception->getMessage().',行号：'.$exception->getLine());
            $res = 0;
        }
        socket_close($socket);  // 关闭Socket
        return $res;
    }
    //通过apiKey获取token，并设置有效期
    public function getToken() {

        if(request()->expectsJson()) {
            $key = request()->header('Access-Key', '');
            $dbKey = DB::Table('setting_sys')->where('key', 'apiKey')->value('value');
            if(!$key || ($key != $dbKey)) {
                return out(0, 'key错误！');
            }
            $redis = Redis::connection('public');
            $data = [];
            $rootUrl = request()->root();
            $ip = request()->ip();
            $key = 'apiToken'.$rootUrl.$ip;
            $tokenR = $redis->get($key);
            if(!$tokenR) {
                $time = time();
                $str = $key.$time.$rootUrl.$ip;
                $token = md5($str);
                if($redis->set($key, $token, 'EX', 72*3600)) {
                    $tokenR = $token;
                }
            }
            $data['token'] = $tokenR;
            $code = $tokenR ? 1 : 0;
            return out($code, 'success', $data);
        }
    }
}
